#include <unistd.h>
#include <termios.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

struct termios oldt, newt;

int l_enter_raw_mode(lua_State *L) 
{
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;

    newt.c_lflag &= ~(ECHO | ICANON | ISIG);
    newt.c_iflag &= ~(IXON | ICRNL);
    newt.c_oflag &= ~OPOST;
    newt.c_cc[VMIN] = 1;
    newt.c_cc[VTIME] = 0;

    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    return 0;
}

int l_exit_raw_mode(lua_State *L) 
{
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return 0;
}

static const struct luaL_Reg raw_mode_lib[] = {
    {"enter_raw_mode", l_enter_raw_mode},
    {"exit_raw_mode",  l_exit_raw_mode },
    {NULL,             NULL            }
};

int luaopen_librawmode(lua_State *L)
{
    luaL_newlib(L, raw_mode_lib);
    return 1;
}